<?php

class Wlib_Model_DbMapper_MultiDynamic extends Wlib_Model_DbMapper_SystemEntity
{
    protected $_insertFields = array();

    protected $_primaryKeyName = 'id';

    protected $_foreignKeyName = null;

    protected $_foreignKeyValue = null;

    public function getInsertFields()
    {
        return $this->_insertFields;
    }

    public function setInsertFields($insertFields)
    {
        $this->_insertFields = $insertFields;
        return $this;
    }

    public function getForeignKeyName()
    {
        return $this->_foreignKeyName;
    }

    public function setForeignKeyName($foreignKeyName)
    {
        $this->_foreignKeyName = $foreignKeyName;
        return $this;
    }

    public function getPrimaryKeyName()
    {
        return $this->_primaryKeyName;
    }

    public function setPrimaryKeyName($primaryKeyName)
    {
        $this->_primaryKeyName = $primaryKeyName;
        return $this;
    }

    public function getForeignKeyValue()
    {
        return $this->_foreignKeyValue;
    }

    public function setForeignKeyValue($foreignKeyValue)
    {
        $this->_foreignKeyValue = $foreignKeyValue;
        return $this;
    }

    /**
     * Сохраняет данные о строках множественного динамического элемента
     *
     * @param array $values Данные одной строки
     * @param int $foreignKeyValue Идентификатор объекта родителя
     */
    public function saveValues($values, $foreignKeyValue)
    {
        foreach ($values['data'] as $row) {
            $this->saveRow($row, $foreignKeyValue);
        }

        if(isset($values['deleted'])) {
            foreach ($values['deleted'] as $deleteId) {
                $this->deleteRowById($deleteId);
            }
        }
    }

    public function saveRow($row, $foreignKeyValue)
    {
        if($row[$this->getPrimaryKeyName()]) {
            if($this->isRowModified($row)) {
                $this->updateRow($row);
            }
        } else {
            $this->insertRow($row, $foreignKeyValue);
        }
    }

    public function isRowModified($row)
    {
        $dbRow = $this->fetchDbRowById($row[$this->getPrimaryKeyName()]);

        if(!$dbRow) {
            return false;
        }

        $isModified = false;
        foreach ($this->getInsertFields() as $oField) {
            if($dbRow[$oField] != $row[$oField]) {
                $isModified = true;
                break;
            }
        }

        return $isModified;
    }

    public function insertRow($row, $foreignKeyValue)
    {
        unset($row[$this->getPrimaryKeyName()]);
        $row[$this->_foreignKeyName] = $foreignKeyValue;
        return $this->insert($row);
    }

    public function updateRow($row)
    {
        $id = $row[$this->getPrimaryKeyName()];
        unset($row[$this->getPrimaryKeyName()]);
        return $this->updateById($row, $id);
    }

    public function deleteRowById($id)
    {
        $this->deleteById($id);
    }

    /**
     * Получает из БД данные строк множественного эелмента
     *
     * @param int $foreignKeyValue
     * @return array Идентификатор объекта родителя
     */
    public function fetchValues($foreignKeyValue)
    {
        $select = $this->select();

        $columns = array_merge(array($this->getPrimaryKeyName()), $this->getInsertFields());
        $select->reset(Zend_Db_Select::COLUMNS);
        $select->columns($columns);

        $select->where('`' . $this->getForeignKeyName() . '` = ?', $foreignKeyValue);

        $dbRowset = $this->fetchAll($select);

        $values = array('data' => $dbRowset->toArray());

        return $values;
    }
}